<?php
/**
 * Created by PhpStorm.
 * User: lcz
 * Date: 2018/8/17
 * Time: 14:56
 * 充值
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Baokim;
use think\Db;

class Recharge extends Api {
	protected $noNeedRight = ['*'];
	protected $noNeedLogin = ['notify'];
	
	public function index(){
		$userId = $this->auth->id;
		$page = input('post.page', 1, 'int');
		
		$model = new \app\common\model\Recharge();
		
		$rows = Db::name('recharge')
			->where(['user_id' => $userId, 'status' => $model::STATUS_Y])
			->field('id, from_unixtime(create_time) as time, amount, pay_type, order_no')
			->page($page)
			->select();
		$this->success(__('查询成功'), $rows);
	}
	
	public function recharge(){
		$userId = $this->auth->id;
		$amount = input('post.amount',0, 'int');
		$payType = input('post.pay_type', 1, 'int');
		$successUrl = input('post.success_url');
		$cancelUrl = input('post.cancel_url');
		
		if(!$amount || $amount < 10000){
			$this->error(__('最少充值10000'));
		}
		
		if(!$successUrl || !$cancelUrl){
			$this->error(__('参数错误'));
		}
		
		switch ($payType) {
			case 1:
				//baokim
				$sn='RE'.time().mt_rand(10000, 99999);
				$data = [
					'order_no' => $sn,
					'user_id' => $userId,
					'amount' => $amount,
					'create_time' => time(),
					'update_time' => time(),
					'success_url' => $successUrl,
					'cancel_url' => $cancelUrl
				];
				
				$res = Db::name('recharge')->insert($data);
				if(!$res) {
					$this->error(__('添加充值订单出错'));
				}
				
				$baokimData = [
					'total_amount' => $amount,
					'payer_name' => '',
					'payer_email' => '',
					'payer_phone_no' => '',
					'shipping_address' => '',
					'order_id' => $sn
				];
				
				$baokim = new Baokim();
				$baokim_url = $baokim->createRequestUrl($baokimData);
				$this->success('', $baokim_url);
				break;
			default:
				$this->error(__('支付方式错误'));
		}
	}
	
	
	/**
	 * 接口数据检验
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 * @throws \think\exception\PDOException
	 */
	public function notify(){
		$data = $this->request->post();
		if($data['token']){
			unset($data['token']);
		}
		
		
		$baokim = new Baokim();
		//检验数据正确性
		$res = $baokim->verifyResponseUrl($data);
		if(!$res) {
			$this->error(__('数据错误'));
		}
		
		$model = new \app\common\model\Recharge();
		$no = $data['order_id'];
		$res = $model->checkRechargeRow($no, $data['transaction_id'], $data['total_amount'], 'baokim');
		if($res) {
			$this->success(__('充值成功'));
		} else {
			$this->error($model->getError());
		}
	}
	
	/**
	 * 获取支付方式
	 */
	public function getPaymentType(){
		$path = $this->request->domain().'/assets/img/';
		$list = [
			['id' => 1, 'name' => 'baokim', 'logo' => $path.'Baokim_logo.png'],
			['id' => 2, 'name' => 'NganLuong.vn', 'logo' => $path.'nganluong.png'],
		];
		
		$this->success('查询成功', $list);
	}
	
}
